<template>
    <div>
        <el-page-header  content="详情页面">
        </el-page-header>
        <el-divider></el-divider>
        <div class="info">
            <h3>修改信息</h3>
            <el-form style="width: 20%;" label-width="80px" :rules="nameRule" ref="infoFormRef" :model="userForm">
                <el-form-item label="头像">
                    <!-- upload组件不会走自己封装好的axios，内部自己封装了一套请求 action头像上传的接口 默认就是post -->
                    <el-upload :action="upload.url" :headers="upload.headers" :auto-upload="false"
                        :on-change="handleChange" :file-list="upload.fileList" ref="uploadRef" :show-file-list="false">
                        <el-avatar :size="100">
                            <img v-if="upload.previewUrl !== undefined" :src="upload.previewUrl" alt="预览图">
                            <!-- <img v-else :src="'/student/v3' + userForm.avatar" alt="用户头像"> -->
                            <img v-else :src="userForm.avatar ? '/student/v3' + userForm.avatar : ''" alt="用户头像">
                        </el-avatar>
                    </el-upload>
                </el-form-item>
                <el-form-item label="账号">
                    <el-input :value="userForm.userName" disabled></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="realName">
                    <el-input v-model="userForm.realName"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit">提交</el-button>
                    <el-button type="info" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-divider></el-divider>

        <div class="password-section">
            <h3>修改密码</h3>
            <el-form ref="passFormRef" style="width: 20%;" label-width="80px" :model="passForm" :rules="rules">
                <el-form-item label="原密码" prop="originalPassword">
                    <el-input show-password v-model="passForm.originalPassword"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input show-password v-model="passForm.password"></el-input>
                </el-form-item>

                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input show-password v-model="passForm.confirmPassword"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handlePassSubmit">提交</el-button>
                    <el-button type="info" @click="handlePassReset">重置</el-button>
                </el-form-item>
            </el-form>

        </div>
    </div>
</template>
<script>
import { getToken} from '@/utils/cookies'
import { updateUser, updatePassword } from '@/api/user'
export default {
    name: 'Mine',
    data() {
        // 姓名校验
        const validateRealName = (rule, value, callback) => {
            const realName = /^[\u4e00-\u9fa5]+$/;
            if (!value.trim()) {
                callback(new Error('请输入姓名'));
            } else if (value.length > 5) { // 直接用value判断长度，因为前面已trim过非空
                callback(new Error('姓名长度不能大于5'));
            } else if (!realName.test(value)) {
                callback(new Error('姓名只能输入中文'));
            } else {
                // 校验通过
                callback();
            }
        };

        //

        // 新旧密码不能一致校验
        const validatePassword = (rule, value, callback) => {
            if (!value.trim()) {
                callback(new Error('请输入新密码'));
            }
            else if (value === this.passForm.originalPassword) {
                callback(new Error('新密码与原密码相同'))
            } else {
                callback()
            }
        }


        // 密码一致性校验
        const confirmPassword = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (this.passForm.password !== value) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }


        return {
            userForm: {},
            upload: {
                url: '/student/v3/prod-api/file/upload',
                headers: { Authorization: 'Bearer ' + getToken() },
                fileList: [],//临时文件，存放即将上传的文件
                previewUrl: undefined,//预览链接
            },

            passForm: {
                password: undefined,
                originalPassword: undefined,
                userId: undefined,
                confirmPassword: undefined,
            },

            // 姓名的表单校验
            nameRule: {
                realName: [
                    {
                        required: true,
                        trigger: 'blur', // 失去焦点时触发校验
                        validator: validateRealName // 调用上面定义的校验函数
                    }
                ]
            },

            rules: {
                originalPassword: [
                    {
                        required: true,//必填属性
                        message: "请输入原密码",//校验提示
                        trigger: "blur",//触发事件
                    }
                ],
                password: [
                    {
                        required: true,//必填属性
                        trigger: "blur",//触发事件
                        validator: validatePassword,
                    }
                ],
                confirmPassword: [
                    {
                        required: true,//必填属性
                        trigger: "blur",//触发事件
                        validator: confirmPassword
                    }
                ],
            },


        }
    },

    
    watch: {
        "$store.state.userForm": {
            deep: true,
            immediate:true,
            handler(n) {
                this.userForm = JSON.parse(JSON.stringify(n));
                // 确保 avatar 有值，若没有则设为空字符串
                if (this.userForm.avatar === undefined) {
                    this.userForm.avatar = '';
                }
            }
        }
    },

    methods: {
        handleChange(file, fileList) {
            console.log(file);
            console.log(fileList);

            if (file.status === 'ready') {
                // 清空前一张的预览链接
                URL.revokeObjectURL(this.upload.previewUrl)

                // 图片预览 URL.createObjectURL把文件信息转成一个临时的文件链接
                this.upload.previewUrl = URL.createObjectURL(file.raw)
                this.upload.fileList = [file]


            }

            if (file.status === 'success') {
                const { response } = file
                // 上传失败
                if (response.code !== 200) return this.$message.error(response.msg)

                // 上传成功

                // 获取头像链接
                this.userForm.avatar = response.data.fileUrl

                // 清空临时文件
                this.upload.fileList = []

                // 清空预览链接
                URL.revokeObjectURL(this.upload.previewUrl)

                this.handleSubmit()
            }
        },

        // 修改信息提交逻辑（作为参考）
        handleSubmit() {
            // 先进行姓名的表单校验
            this.$refs.infoFormRef.validate(valid => {
                //校验不通过则不能提交
                if (!valid) return

                // 1. 判断是否有头像需要上传，有文件则上传
                if (this.upload.fileList.length > 0) {
                    this.$refs["uploadRef"].submit();
                    return;
                }

                // 2. 没有文件则修改用户信息
                const { userId, realName, avatar } = this.userForm;
                updateUser({ userId, realName, avatar }).then(res => {
                    console.log(res);
                    this.$store.dispatch("getUserInfo")
                    this.$message.success(res.msg || '修改信息成功');
                })
            })

        },

        handleReset() {
            this.userForm = JSON.parse(JSON.stringify(this.$store.state.userForm))
            this.upload.fileList = []
            this.upload.previewUrl = undefined
        },


        //密码的提交重置
        handlePassSubmit() {
            this.$refs.passFormRef.validate(async isSubmit => {
                if (isSubmit) {
                    //校验通过
                    const { password, originalPassword, userId } = this.passForm
                    await updatePassword({ password, originalPassword, userId }).then(res => {
                        this.$message.success('修改密码成功');
                        // 重置密码表单
                        this.handlePassReset();
                    })
                }
            })
        },

        handlePassReset() {
            this.$refs.passFormRef.resetFields();
        },

    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-divider--horizontal {
    height: 2px;
    margin: 24px 0 !important;
}
</style>
